package com.example.grape_effect.effet.effect

import com.example.grape_effect.gl.common.ShaderParameter
import com.lammy.grapeeffect.interpolator.LYInterpolator
import com.example.grape_effect.interpolator.UniformAccelerationInterpolator

/**
 * 径向模糊特效
 */
class RadialBlurEffect : LYEffect() {
    override var fragmentShader =
        """ precision highp float;
 varying highp vec2 textureCoordinate;
 uniform sampler2D inputTexture;
 const int sampleCount = 6; //采样点
 uniform float intensity ; //取值范围 建议 0 - 0.1
/*********************************/
 // blur 优化可以降采样，再进行此操作
 //算法参考https://blog.csdn.net/puppet_master/article/details/54566397
 /*********************************/
 void main()
 {
     vec2 dir = textureCoordinate - vec2(0.5, 0.5);
     vec4 color;
     for(int i = 0; i < sampleCount; i ++) {
         vec2 uv = textureCoordinate - float(i)* dir * intensity;
         color = color + texture2D(inputTexture, uv);
     }
     gl_FragColor = color/float(sampleCount);
 }
"""

    lateinit var interpolater:LYInterpolator
    lateinit var interpolater2:LYInterpolator
    init{
        name = "radialBlurEffect"
        duration = 2000L
        // 扩撒
          interpolater = UniformAccelerationInterpolator(1000, 0f, 0.1f, 0.0f)
        // 还原
          interpolater2 = UniformAccelerationInterpolator(1000, 0.1f, 0.0f, 0.0f)

    }
    override fun addParameters() {
        super.addParameters()
        parameters["intensity"] = ShaderParameter(
            "intensity",
            ShaderParameter.TYPE_UNIFORM,
            ShaderParameter.VALUE_TYPE_FLOAT
        )
    }

    override fun setDefaultParameterValues() {
        super.setDefaultParameterValues()
        parameters["intensity"]?.value = 0.1f

    }

    fun setIntensity(intensity: Float) {
        parameters["intensity"]?.value = intensity
    }

    fun updateIntensity(executedTime: Long) {
        if (executedTime > duration/2) {
            if(executedTime < duration) {
                var intensity2 = interpolater2.getValue(executedTime - duration/2)
                setIntensity(intensity2)
            }
            return
        }
        var intensity = interpolater.getValue(executedTime)
        setIntensity(intensity)
    }

    // must use in glThread
    override fun draw() {
        updateIntensity(System.currentTimeMillis() - startTime)
        super.draw()
    }

}